import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { getDetail, getPing } from "../../apis/api";
import { Input,Button } from "antd";
import { Avatar, List } from 'antd';

import { UploadOutlined } from '@ant-design/icons';
import {  message, Upload } from 'antd';
import type { GetProp, UploadFile, UploadProps } from 'antd';

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
function Detail() {
    const id=useParams().id
    const [data,setData]=useState('')
    const aa=async()=>{
        const res=await getDetail(id)
        console.log(res.data.comments);
        setData(res.data)
    }
    useEffect(()=>{
        aa()
    },[])

    const [value,setValue]=useState('')
    const onchangeping=async()=>{
        const res=await getPing({
            userId:47529555,// 47529555 用户id
        content:value,//评论内容
      //  commentId:number,//评论ID（非必填，回复评论时使用）
        articleId:id // 文章id 90

        })
        console.log(res);
        aa()
        setValue('')
        
    }



    const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [uploading, setUploading] = useState(false);

  const handleUpload = () => {
    const formData = new FormData();
    fileList.forEach((file) => {
      formData.append('files[]', file as FileType);
    });
    setUploading(true);
    // You can use any AJAX library you like
    fetch('https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload', {
      method: 'POST',
      body: formData,
    })
      .then((res) => res.json())
      .then(() => {
        setFileList([]);
        message.success('upload successfully.');
      })
      .catch(() => {
        message.error('upload failed.');
      })
      .finally(() => {
        setUploading(false);
      });
  };

  const props: UploadProps = {
    onRemove: (file) => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    beforeUpload: (file) => {
      setFileList([...fileList, file]);

      return false;
    },
    fileList,
  };

  const [isShow, setIsShow]=useState(false)

  const huifu=()=>{
    setIsShow(!isShow)
  }
  const [sade,setSade]=useState('')
  const [xiao,setXiao]=useState('')
  const oncnangehui=async(commentId)=>{
    if(sade===''){
      alert('请输入回复内容')
    }else{
const res=await getPing({
      userId:47529555,// 47529555 用户id
        content:sade,//评论内容
       commentId,//评论ID（非必填，回复评论时使用）
        articleId:id // 文章id 90

    })
    console.log(res);
    setSade('')
    aa()
    setIsShow(false)
    }
    
    // setXiao(res)
  }
    return (
        <div style={{display:'flex'}}>
            <div style={{background:'',width:'300px',height:'100vh'}}>
                <div style={{textAlign:'center'}}>
                    <img style={{width:'200px',height:'200px',borderRadius:'50%'}} src="https://ts1.tc.mm.bing.net/th/id/OIP-C.U1UG7FN50qzrntU8he3s9wAAAA?w=186&h=186&c=8&rs=1&qlt=9
                0&o=6&cb=12&dpr=1.3&pid=3.1&rm=2" alt="" />
                <h2>我的博客小测</h2>
                <p>学而知不足</p>
                <h3>热门文章</h3>
                </div>
                <br />
                <ul style={{lineHeight:'40px'}}>
                    <li>koa-react-ssr 学习</li>
                    <li>koa-react-ssr 学习</li>
                    <li>koa-react-ssr 学习</li>
                    <li>koa-react-ssr 学习</li>
                    <li>koa-react-ssr 学习</li>
                </ul>
            </div>
            <div className='add' style={{background:'',width:'800px',height:'100vh'}}>
                <h1 style={{textAlign:'center'}}>{data.title}</h1>
                <p>用来方便学习，免去学习常见过程走捷径不是客户打个撒动感单车</p>
                <Upload {...props}>
        <Button icon={<UploadOutlined />}>上传文件</Button>
      </Upload>
      {/* <Button
        type="primary"
        onClick={handleUpload}
        disabled={fileList.length === 0}
        loading={uploading}
        style={{ marginTop: 16 }}
      >
        {uploading ? 'Uploading' : 'Start Upload'}
      </Button> */}
                <p>创建的内容如下：</p>
                <p>{data.content}</p>
                <p>创建时间：<span style={{color:'red'}}>{data.createdAt}</span></p>
                <p>浏览数量：<span style={{color:'red'}}>{data.viewCount}</span></p>
                <Input.TextArea value={value} onChange={(e)=>setValue(e.target.value)}  rows={4} />
                <Button onClick={()=>onchangeping()}>评论</Button>
                {/* {data.comments} */}
                <List
    itemLayout="horizontal"
    dataSource={data.comments}
    renderItem={(item, index) => (
      <List.Item>
        <List.Item.Meta
          avatar={<Avatar src={`https://api.dicebear.com/7.x/miniavs/svg?seed=${index}`} />}
          title={<a href="https://ant.design">{item.user.username}</a>}
          description={
            <div>
               <span>评论时间：{item.createdAt}</span> <br />
                <span>评论内容:{item.content}</span>
                <Button onClick={huifu}>回复评论</Button>
                
                {item&&item.replies.map((v,i)=>{
                    return <div key={i}>
                      <span>回复内容：{v.content} | 回复时间：{v.createdAt} | 回复者：{v.user.username}</span>
                    </div>
                  })}
                  
                {isShow?<div>
                  <Input.TextArea rows={4} value={sade} onChange={(e)=>setSade(e.target.value)}/>
                  <Button onClick={()=>oncnangehui(item.id)}>回复</Button>
                  </div>:''}
                  
                
            </div>
          }
        />
      </List.Item>
    )}
  />
                </div>
            
            
        </div>
    );
}

export default Detail;